﻿using System.Text.RegularExpressions;

namespace Zo.Extensions
{
    /// <summary>
    /// 邮箱相关的扩展。
    /// </summary>
    public static class EmailExtensions
    {
        /// <summary>
        /// 验证 Email 的正则表达式。
        /// </summary>
        private static readonly Regex _emailExpression = new Regex(@"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$",
            RegexOptions.Singleline | RegexOptions.Compiled);

        /// <summary>
        /// 是否电子邮箱。
        /// </summary>
        /// <param name="target">当前字符串。</param>
        /// <returns>是否电子邮箱。</returns>
        public static bool IsEmail(this string target) => !string.IsNullOrEmpty(target) && _emailExpression.IsMatch(target);

        public static string GetEmailToLower(this string source)
        {
            if (string.IsNullOrWhiteSpace(source))
                return source;

            if (!_emailExpression.IsMatch(source))
                return source;

            var emailArray = source.Split('@');

            if (emailArray.Length != 2)
            {
                return source;
            }

            var first = emailArray[0];
            var last = emailArray[1];

            if (!string.IsNullOrWhiteSpace(first) && !string.IsNullOrWhiteSpace(last))
            {
                return first + "@" + last.ToLower();
            }

            return source;
        }

        /// <summary>
        /// 判断当前邮箱是否与指定的邮箱相匹配。
        /// </summary>
        /// <param name="source">当前邮箱。</param>
        /// <param name="email">目标邮箱。</param>
        /// <returns>相同则返回 True，否则返回 False。</returns>
        public static bool EqualEmail(this string source, string email)
        {
            var current = source.GetEmailToLower();
            var target = email.GetEmailToLower();

            return current == target;
        }
    }
}